<?php

namespace App\Console\Command;

use DI\Annotation\Inject;
use Monolog\Logger;
use Noodlehaus\Config;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Wonfu\Core\AppConfig;
use Spatie\Async\Pool;


class AsyncTest extends  Command
{
    protected static $defaultName = 'Async:test';

    /**
     * @Inject("appConfig")
     * @var AppConfig
     */
    private $appConfig;

    /**
     * @Inject
     * @var Config
     */
    private $envConfig;


    protected function configure()
    {
        $this->setDescription('Async test.')
            ->setHelp('This command allows you to');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {

        $output->writeln("process run in ".getmypid());
        $pool = Pool::create();
        $pool->autoload(APP_ROOT.'/config/di.php');
        $things = [1,11,11,33,23,2];
        $container = AppConfig::getContainer();
        foreach ($things as $thing) {
            $pool->add(function () use ($thing,$output,$container) {
                sleep($thing);
                /** @var Logger $logger */
                $logger = $container->get(LoggerInterface::class);
                $logger->warning($thing);
                return $thing;
            })->then(function ($output)use($container) {

                /** @var Logger $logger */
                $logger = $container->get(Logger::class);
                // Handle success
                dump($output);
                $logger->info('something right');
            })->catch(function (\Throwable $exception) {
                // Handle exception
                echo $exception->getMessage();
            });
        }

        $pool->wait();
        return 0;

    }


}